package com.itboye.sunsun.utils;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.Reference;
import java.lang.ref.WeakReference;
import java.util.concurrent.TimeUnit;

import com.itboye.sunsun.R;
import com.itboye.sunsun.Application.App;
import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiscCache;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.cache.memory.BaseMemoryCache;
import com.nostra13.universalimageloader.cache.memory.impl.UsingFreqLimitedMemoryCache;
import com.nostra13.universalimageloader.cache.memory.impl.WeakMemoryCache;
import com.nostra13.universalimageloader.core.DefaultConfigurationFactory;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
import com.nostra13.universalimageloader.core.download.BaseImageDownloader;
import com.nostra13.universalimageloader.core.download.ImageDownloader;
import com.nostra13.universalimageloader.utils.StorageUtils;
import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.widget.ImageView;

/**
 * 基于 OKhttp的ImageLoader
 * @author Young
 *
 */
public class XImageLoader {

	 
	static{
		
		DisplayImageOptions options = new DisplayImageOptions.Builder()
				  // 设置图片下载期间显示的图片
				.showImageOnLoading(R.drawable.homepage_off) 
				.showImageForEmptyUri(R.drawable.homepage_off)// 设置图片Uri为空或是错误的时候显示的图片
				.showImageOnFail(R.drawable.homepage_off) // 设置图片加载或解码过程中发生错误显示的图片
				.cacheInMemory(true)// 设置下载的图片是否缓存在内存中
				.cacheOnDisk(true)// 设置下载的图片是否缓存在SD卡中
				//.displayer(new RoundedBitmapDisplayer(20))// 设置成圆角图片
				.build(); // 创建配置过得DisplayImageOption对象 

		
		File cacheDir = StorageUtils.getOwnCacheDirectory(App.ctx, "sunsun/Cache");  
		ImageLoaderConfiguration config = new ImageLoaderConfiguration  
			    .Builder(App.ctx)  
				    .memoryCacheExtraOptions(480, 800) // max width, max height，即保存的每个缓存文件的最大长宽  
				  //  .discCacheExtraOptions(480, 800, CompressFormat.JPEG, 75, null) // Can slow ImageLoader, use it carefully (Better don't use it)/设置缓存的详细信息，最好不要设置这个  
				    .threadPoolSize(4)//线程池内加载的数量  
				    .threadPriority(Thread.NORM_PRIORITY )  
				    .denyCacheImageMultipleSizesInMemory()  
				    //.memoryCache(new UsingFreqLimitedMemoryCache(2 * 1024 * 1024)) // You can pass your own memory cache implementation/你可以通过自己的内存缓存实现  
				    .memoryCache(new WeakMemoryCache())
				     
				    .memoryCacheSize(15 * 1024 * 1024)    
				    
				    .diskCacheSize(80 * 1024 * 1024)    
				    .diskCacheFileNameGenerator(new Md5FileNameGenerator())//将保存的时候的URI名称用MD5 加密  
				    
				    
				    .tasksProcessingOrder(QueueProcessingType.LIFO)  
				    .diskCacheFileCount(100) //缓存的文件数量  
				    .diskCache(new UnlimitedDiscCache(cacheDir))//自定义缓存路径  
				  //  .defaultDisplayImageOptions(DisplayImageOptions.createSimple())  
				    .defaultDisplayImageOptions(options)
				   // .imageDownloader(new BaseImageDownloader(App.ctx, 5 * 1000, 30 * 1000)) // connectTimeout (5 s), readTimeout (30 s)超时时间
				    .imageDownloader(new DownloadImageFromNetWork(App.ctx,  5 * 1000, 30 * 1000))
				    .writeDebugLogs() // Remove for release app  
				    .build();//开始构建  
				    // Initialize ImageLoader with configuration.  

		com.nostra13.universalimageloader.core.ImageLoader.getInstance().init(config);//全局初始化此配置  
		
		
		
		 
	}
	
	private static class DownloadImageFromNetWork extends BaseImageDownloader{

		
		public DownloadImageFromNetWork(Context context, int connectTimeout, int readTimeout) {
			super(context, connectTimeout, readTimeout);
		}
		@Override
		protected InputStream getStreamFromNetwork(String arg0, Object arg1) throws IOException {
			
			try {
				OkHttpClient client = new OkHttpClient();
				client.setConnectTimeout(connectTimeout, TimeUnit.MILLISECONDS);
				client.setReadTimeout(readTimeout, TimeUnit.MILLISECONDS);
				Request request = new Request.Builder().url(arg0).build();
				Response response = client.newCall(request).execute();
				if (!response.isSuccessful()) {
					return null;
				} else {
					return response.body().byteStream();
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				return null;
			}
		}
		
		
	}
	public static void load(String uri,ImageView imageView){
		
		ImageLoader.getInstance().displayImage(uri, imageView);
		
		System.out.println("download img--->"+uri);
	}
}
